from django.db import models
from user.models import Cashier, Customer
from product.models import Product

# 订单表
class Order(models.Model):
    PAYMENT_METHOD = (
        ("cash", "现金支付"),
        ("wechat", "微信支付"),
        ("alipay", "支付宝"),
        ("card", "银行卡支付"),
    )
    ORDER_STATUS = (
        ("pending", "待支付"),
        ("paid", "已支付"),
        ("cancelled", "已取消"),
    )
    order_sn = models.CharField(max_length=32, unique=True, verbose_name="订单编号")  # 生成规则：时间戳+随机数
    cashier = models.ForeignKey(Cashier, on_delete=models.SET_NULL, null=True, related_name="cashier_orders", verbose_name="收银员")
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, related_name="customer_orders", verbose_name="网购客户")  # 线下订单可为空
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="订单总金额")
    discount = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name="折扣金额")
    payment_method = models.CharField(max_length=20, choices=PAYMENT_METHOD, verbose_name="支付方式")
    status = models.CharField(max_length=20, choices=ORDER_STATUS, default="pending", verbose_name="订单状态")
    pay_time = models.DateTimeField(null=True, blank=True, verbose_name="支付时间")
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        verbose_name = "订单"
        verbose_name_plural = verbose_name
        db_table = "order_order"

    def __str__(self):
        return self.order_sn

# 订单项表（订单与商品的多对多关联）
class OrderItem(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="order_items", verbose_name="所属订单")
    product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="商品")
    quantity = models.IntegerField(default=1, verbose_name="购买数量")
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="购买单价")  # 记录下单时价格

    class Meta:
        verbose_name = "订单项"
        verbose_name_plural = verbose_name
        db_table = "order_orderitem"

    def __str__(self):
        return f'{self.product.name} x {self.quantity}'

    @property
    def subtotal(self):
        return self.price * self.quantity
